import json
from os import error
from aiogram import Router, F, types
from aiogram.types import ReplyKeyboardRemove
from sqlalchemy import JSON

from utils.api_urls import APIUrls
from utils.api_requests import post_request
from utils.auth import encode_jwt


router = Router(name=__name__)


@router.message(F.content_type.in_({"contact"}))
async def create_reference(message: types.Message):

    chat_id: int = message.chat.id

    if message.from_user:
        tg_user_id: int = message.from_user.id

    if message.contact:
        phone: str = message.contact.phone_number
        first_name: str = message.contact.first_name
    else:
        await message.answer(f"Не удалось получить номер телефона")

    jwt_payload = {
        "sub": tg_user_id,
        "chat_id": chat_id,
        "tg_user_id": tg_user_id,
        "phone": phone,
        "first_name": first_name,
    }

    token = encode_jwt(jwt_payload)

    response = await post_request(
        url=APIUrls.create_reference,
        data={"token": token},
    )

    if "success" in response["status"].lower():
        await message.answer(
            f"Спасибо, {first_name}.\nУчетная запись привязана",
            reply_markup=ReplyKeyboardRemove(),
        )

    elif "error" in response["status"].lower():
        error_message: str = response["message"]
        await message.answer(
            f"Ошибка при получении учетной записи.\n{error_message})",
            reply_markup=ReplyKeyboardRemove(),
        )

    else:
        await message.answer(
            "Что то пошло не так",
            reply_markup=ReplyKeyboardRemove(),
        )
